package com.rtx.edi.platform.rule.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rtx.edi.model.api.po.PlApiMappingStructure;
import com.rtx.edi.model.rule.dto.PlSerialRuleDto;
import com.rtx.edi.platform.rule.bean.PlSerialRule;
import com.rtx.edi.platform.rule.mapper.PlSerialRuleMapper;
import com.rtx.edi.platform.rule.service.PlSerialRuleService;


@Service
public class PlSerialRuleServiceImpl extends ServiceImpl<PlSerialRuleMapper,PlSerialRule> implements PlSerialRuleService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public void selectPlSerialRule(Page<PlSerialRule> pageParam, PlSerialRule plSerialRule) {
		 LambdaQueryWrapper<PlSerialRule> query = Wrappers.lambdaQuery();
		 if(plSerialRule!=null) {
			 query.like(StringUtils.hasText(plSerialRule.getName()),PlSerialRule::getName,plSerialRule.getName())
			 .eq(plSerialRule.getCode()!=null,PlSerialRule::getCode,plSerialRule.getCode())
			 .eq(plSerialRule.getType()!=null, PlSerialRule::getType, plSerialRule.getType());
		 }
		 
		 baseMapper.selectPage(pageParam,query);
	}
	
	@Override
	public boolean addPlSerialRule(PlSerialRule plSerialRule) {
		// 验证非空字段
		checkField(plSerialRule);
		LambdaQueryWrapper<PlSerialRule> query = Wrappers.lambdaQuery();
		query.eq(plSerialRule.getName()!=null, PlSerialRule::getName, plSerialRule.getName())
		.eq(plSerialRule.getCode()!=null, PlSerialRule::getCode, plSerialRule.getCode())
		.eq(plSerialRule.getType()!=null, PlSerialRule::getType, plSerialRule.getType());
		Assert.isTrue(!baseMapper.exists(query),"流水号规则已存在");
		
		plSerialRule.setId(null);
		return baseMapper.addPlSerialRule(plSerialRule) == 1; // 新增
		
	}

	@Override
	@Transactional
	public void deletePlSerialRule(List<PlSerialRuleDto> list) {
		for(PlSerialRuleDto dto:list) {
			
			baseMapper.deleteById(dto.getId()); // 删除
		}
		
	}
	
	/**
	 * 验证非空字段
	 * @param plSerialRule
	 */
	private void checkField(PlSerialRule plSerialRule) {
		 Assert.notNull(plSerialRule.getName(),"流水号名称不能为空");
		 Assert.notNull(plSerialRule.getCode(),"流水号code不能为空");
		 Assert.notNull(plSerialRule.getType(),"流水号生成类型不能为空");
	}

	@Override
	public PlSerialRule selectPlSerialRuleById(String id) {
		 LambdaQueryWrapper<PlSerialRule> query = Wrappers.lambdaQuery();
		 query.eq( PlSerialRule::getId, Integer.parseInt(id));
		 
		return baseMapper.selectOne(query);
	}

	@Override
	public String getKeyByRule(PlSerialRule plSerialRule) {
		String keyname=plSerialRule.getCode();
		String prefix=plSerialRule.getType();
		String wmskey = null;
        Integer count = baseMapper.selectWmskey(keyname);
        if(count == null){
            count = 0;
            baseMapper.insertNcounter(keyname);
        }else{
        	baseMapper.updateNcounter(keyname);
        }
        if(StringUtils.hasText(prefix)){
            if(prefix.length() > 2){
                prefix = prefix.substring(0,2);
            }
            wmskey = prefix + String.format("%0" + (10 - prefix.length()) + "d",++count);
        }else{
            wmskey = String.format("%010d",++count);
        }
        return wmskey;
		
	}

	@Override
	public String handleSerialnumber(String targetjson,List<PlApiMappingStructure> structureList) {
		JSONObject targetJSON = JSON.parseObject(targetjson);
		logger.info("targetJSON before"+JSON.toJSONString(targetJSON));
		String SerialnumbersTmp="";
		
		for(PlApiMappingStructure structure:structureList) {
			if(null==structure.getSerialnumber()) continue;
			if("serialnumber".equals(structure.getMappingType())) {
				PlSerialRule rule=this.selectPlSerialRuleById(structure.getSerialnumber());
				// 自动生成流水号
				if(!SerialnumbersTmp.equals(structure.getSerialnumber())) {
					String key="";
					 
					for(String column:targetJSON.keySet()) {
						if(column.equals(structure.getTargetFieldName())) {
							if("".equals(key)) {
								key=this.getKeyByRule(rule);
							}
							targetJSON.put(column, key);
						}
					}
					// 明细 
					if(targetJSON.containsKey("明细字段")) {
						List<JSONObject> details =JSON.parseArray(targetJSON.getString("明细字段"), JSONObject.class);
						for(JSONObject detail:details) {
							for(String fildname:detail.keySet()) {
								if(fildname.equals(structure.getTargetFieldName())) {
									if("".equals(key)) {
										key=this.getKeyByRule(rule);
									}
									// 订单流水号
									detail.put(fildname, key);
								}
								
							}
							
						}
						targetJSON.put("明细字段", details);
					}
				}
				
				
				SerialnumbersTmp=structure.getSerialnumber();
			}else if("seriallinenumber".equals(structure.getMappingType())){
				if(targetJSON.containsKey("明细字段")) {
					List<JSONObject> details =JSON.parseArray(targetJSON.getString("明细字段"), JSONObject.class);
					int count=0;
					for(JSONObject detail:details) {
						for(String fildname:detail.keySet()) {
							if(fildname.equals(structure.getTargetFieldName())) {
								// 行号
								detail.put(fildname, String.format("%05d",++count));
							}
							
						}
						
					}
					targetJSON.put("明细字段", details);
					
				}
				
				
			}

		}
		logger.info("targetJSON after"+JSON.toJSONString(targetJSON));
		return JSON.toJSONString(targetJSON);
	}


}
